package org.gg.boom.kernel.validate;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import org.springframework.stereotype.Component;

@Component
public class FieldUniqueService {
    /**
     * 校验字段唯一性
     *
     * @return
     */
    public boolean fieldUnique(FieldUniqueParam param) {
        validateParam(param);
        // 校验唯一性
        return doValidate(param);
    }

    private boolean doValidate(FieldUniqueParam param) {
        long resultCount = 0;
        // 不排除当前记录，不排除逻辑删除的内容
        if (!param.getExcludeCurrentRecord()
                && !param.getExcludeLogicDeleteItems()) {
            String sqlTemplate = "select count(*) from {} where {} = {0}";
            String finalSql = StrUtil.format(sqlTemplate, param.getTableName(), param.getColumnName());
            resultCount = SqlRunner.db().selectCount(finalSql, param.getValue());
        }

        // 不排除当前记录，排除逻辑删除的内容
        if (!param.getExcludeCurrentRecord()
                && param.getExcludeLogicDeleteItems()) {
            String sqlTemplate = "select count(*) from {} where {} = {0}  and ({} is null or {} <> '{}')";
            String finalSql = StrUtil.format(sqlTemplate,
                    param.getTableName(),
                    param.getColumnName(),
                    param.getLogicDeleteFieldName(),
                    param.getLogicDeleteFieldName(),
                    param.getLogicDeleteValue());
            resultCount = SqlRunner.db().selectCount(finalSql, param.getValue());
        }

        // 排除当前记录，不排除逻辑删除的内容
        if (param.getExcludeCurrentRecord()
                && !param.getExcludeLogicDeleteItems()) {

            String sqlTemplate = "select count(*) from {} where {} = {0} and {} <> {1}";
            String finalSql = StrUtil.format(sqlTemplate, param.getTableName(), param.getColumnName(), param.getIdFieldName());
            resultCount = SqlRunner.db().selectCount(finalSql, param.getValue(), param.getId());
        }

        // 排除当前记录，排除逻辑删除的内容
        if (param.getExcludeCurrentRecord()
                && param.getExcludeLogicDeleteItems()) {

            String sqlTemplate = "select count(*) from {} where {} = {0} and {} <> {1} and ({} is null or {} <> '{}')";
            String finalSql = StrUtil.format(sqlTemplate,
                    param.getTableName(),
                    param.getColumnName(),
                    param.getIdFieldName(),
                    param.getLogicDeleteFieldName(),
                    param.getLogicDeleteFieldName(),
                    param.getLogicDeleteValue());
            resultCount = SqlRunner.db().selectCount(finalSql, param.getValue(), param.getId());
        }

        // 如果大于0，代表不是唯一的当前校验的值
        return resultCount <= 0;
    }

    private void validateParam(FieldUniqueParam param) {

    }
}
